﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SenGe.Application;
using SenGe.Domain;
using SenGe.Domain.Utils;
using System.Security.Claims;

namespace SenGe.Web.Controllers
{
    /// <summary>
    /// 账户相关控制器
    /// </summary>
    public class AccountController : Controller
    {
        private readonly ISenUserService _userService;
        private readonly ILogger<AccountController> _logger;
        private readonly IConfiguration _config;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="config"></param>
        /// <param name="logger"></param>
        /// <param name="senUserService"></param>
        public AccountController(IConfiguration config, ILogger<AccountController> logger, ISenUserService senUserService)
        {
            _config = config;
            _logger = logger;
            _userService = senUserService;
        }

        /// <summary>
        /// 默认登录页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> Login()
        {
            if (User.Identity?.IsAuthenticated ?? false)
            {
                return RedirectToAction("Index", "Home");
            }
            var checkConnection = await _userService.CheckDbConnection();
            ViewBag.CheckConnection = checkConnection ? 1 : 0;
            //return View();
            return View(new LoginModel() { UserName = "admin", Password = string.Empty, ResultMessage = string.Empty });
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="model">登录模型</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> Login([FromForm] LoginModel model)
        {
            //验证输入
            model.ResultMessage = string.Empty;
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            //验证登录用户名和密码
            var dbItem = await _userService.GetUserByUserName(model.UserName);
            if (dbItem == null || !SecurePasswordHasher.VerifyPassword(dbItem.PassWord, model.Password))
            {
                model.ResultMessage = "登录用户名或密码错误！";
                return View(model);
            }

            // 使用Cookie认证方案进行登录
            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, dbItem.Id.ToString()),
                new Claim(ClaimTypes.Name, dbItem.Name),
                new Claim("avatar",dbItem.Avatar??"")
            };
            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var principal = new ClaimsPrincipal(identity);
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

            await _userService.UpdateLastLoginTime(dbItem);
            return RedirectToAction("Index", "Home");
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public IActionResult Register()
        {
            return View();
        }

        /// <summary>
        /// 提交注册
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> Register([FromForm] UserRegisterModel model)
        {
            model.ResultMessage = string.Empty;
            if (!ModelState.IsValid) return View(model);
            UserRegisterCheckResult checkResult = await _userService.CheckRegisterInfo(model);
            if (checkResult == UserRegisterCheckResult.NameExists)
            {
                model.ResultMessage = "该用户昵称已存在！";
                return View(model);
            }
            else if (checkResult == UserRegisterCheckResult.UserNameExists)
            {
                model.ResultMessage = "该用户名已存在！";
                return View(model);
            }
            model.UpdatedUserId = 0;
            model.UpdatedUserName = "用户自行注册";
            if (await _userService.AddOrUpdateUser(model))
            {
                model.Result = 1;
                model.ResultMessage = "注册成功！";
            }
            return View(model);
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Login");
        }
    }
}
